import { JSBridge } from "../JSBridge";
import { TouTiaoConfig } from "./TouTiaoConfig";
import QuLe from "../QuLe";

export default class TouTiaoRecorder {

    private static _instance: TouTiaoRecorder = null;
    private constructor() { }
    static get instance() {
        if (!TouTiaoRecorder._instance) {
            TouTiaoRecorder._instance = new TouTiaoRecorder();
        }
        return TouTiaoRecorder._instance;
    }

    recorderManager: any;
    private onStopedRecord: Function;

    /** 开始录屏 */
    startRecord() {
        this.onStopedRecord = null;
        let tt = JSBridge.getTTObj();
        if (!tt) return;
        if (!this.recorderManager) {
            let recorderManager = this.recorderManager = tt.getGameRecorderManager();
            recorderManager.onStart((res) => {
                console.log('开始录屏: ' + JSON.stringify(res));
            });
            recorderManager.onPause((res) => {
                console.log('暂停录屏: ' + JSON.stringify(res));
            });
            recorderManager.onStop(res => {
                console.log('结束录屏，视频地址: ' + res.videoPath);
                if (this.onStopedRecord) {
                    this.onStopedRecord(res.videoPath);
                }
            });
            recorderManager.onError((err) => {
                console.log('录屏错误: ' + JSON.stringify(err));
            });
        }
        this.recorderManager.start({ duration: 300 });//单位s,最大支持300
    }

    /**
     * 结束录屏
     * @param onStopedRecord onStopedRecord(videoPath),剪辑失败videoPath返回null
     */
    stopRecord(onStopedRecord: Function) {
        this.onStopedRecord = onStopedRecord;
        if (this.recorderManager) {
            this.recorderManager.stop();
        } else {
            if (onStopedRecord) {
                onStopedRecord(null);
            }
        }
    }

    /**
     * 分享录屏后得到的视频
     * @param recordVideoPath 录屏完成时得到视频地址
     * @param onShareFinish onShareFinish(success: boolean)
     */
    shareVideo(recordVideoPath: string, query: string = '', onShareFinish?: Function) {
        if (!recordVideoPath) {
            console.error('暂无录制保存的视频');
            onShareFinish && onShareFinish(false);
            return;
        }
        let tt = JSBridge.getTTObj();
        if (!tt) {
            onShareFinish && onShareFinish(false);
            return;
        }
        tt.shareAppMessage({
            channel: "video",
            templateId: QuLe.instance.remoteConfig.toutiaoShareTemplateId,
            query: query,
            extra: {
                videoPath: recordVideoPath
            },
            success() {
                console.log("头条视频分享成功");
                if (onShareFinish) {
                    onShareFinish(true);
                }
            },
            fail(err) {
                console.log("头条视频分享失败:" + JSON.stringify(err));
                if (onShareFinish) {
                    onShareFinish(false);
                }
            }
        });
    }

}
